package pannel.product;

import javax.swing.*;
import java.awt.*;
import java.io.File;

public class ProductDialog extends JDialog {
    private JTextField nameField;
    private JTextField priceField;
    private JTextField stockField;
    private JTextField imagePathField;
    private JButton browseButton;
    private boolean confirmed = false;
    private Product product;
    private JLabel previewLabel;

    public ProductDialog(Frame owner, String title, Product product) {
        super(owner, title, true);
        this.product = product;
        setupDialog();
    }

    private void setupDialog() {
        setLayout(new BorderLayout());
        JPanel mainPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.fill = GridBagConstraints.HORIZONTAL;

        // 商品名称
        addField(mainPanel, gbc, "商品名称:", nameField = new JTextField(20), 0);

        // 价格
        addField(mainPanel, gbc, "价格:", priceField = new JTextField(20), 1);

        // 库存
        addField(mainPanel, gbc, "商品库存:", stockField = new JTextField(20), 2);

        // 图片路径
        gbc.gridx = 0;
        gbc.gridy = 3;
        gbc.gridwidth = 1;
        mainPanel.add(new JLabel("图片路径:"), gbc);

        imagePathField = new JTextField(20);
        gbc.gridx = 1;
        gbc.gridwidth = 1;
        mainPanel.add(imagePathField, gbc);

        browseButton = new JButton("浏览");
        gbc.gridx = 2;
        mainPanel.add(browseButton, gbc);

        // 预览
        previewLabel = new JLabel();
        previewLabel.setPreferredSize(new Dimension(100, 100));
        previewLabel.setHorizontalAlignment(JLabel.CENTER);
        gbc.gridx = 0;
        gbc.gridy = 4;
        gbc.gridwidth = 3;
        mainPanel.add(previewLabel, gbc);

        // 填充现有数据
        if (product != null) {
            nameField.setText(product.getName());
            priceField.setText(String.valueOf(product.getPrice()));
            stockField.setText(String.valueOf(product.getStock()));
            imagePathField.setText(product.getImagePath());
            updatePreview(product.getImagePath());
        }

        // 按钮面板
        JPanel buttonPanel = new JPanel();
        JButton okButton = new JButton("确定");
        JButton cancelButton = new JButton("取消");
        buttonPanel.add(okButton);
        buttonPanel.add(cancelButton);

        // 事件处理
        setupEventHandlers(okButton, cancelButton);

        add(mainPanel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);

        pack();
        setLocationRelativeTo(null);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }

    private void setupEventHandlers(JButton okButton, JButton cancelButton) {
        browseButton.addActionListener(e -> {
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
                public boolean accept(File f) {
                    String name = f.getName().toLowerCase();
                    return f.isDirectory() || name.endsWith(".jpg") || name.endsWith(".png")
                            || name.endsWith(".gif") || name.endsWith(".jpeg");
                }

                public String getDescription() {
                    return "Image Files (*.jpg, *.png, *.gif, *.jpeg)";
                }
            });

            if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
                String path = fileChooser.getSelectedFile().getAbsolutePath();
                imagePathField.setText(path);
                updatePreview(path);
            }
        });

        okButton.addActionListener(e -> {
            if (validateInput()) {
                confirmed = true;
                dispose();
            }
        });

        cancelButton.addActionListener(e -> dispose());
    }

    private void addField(JPanel panel, GridBagConstraints gbc, String labelText, JComponent field, int row) {
        gbc.gridx = 0;
        gbc.gridy = row;
        gbc.gridwidth = 1;
        panel.add(new JLabel(labelText), gbc);

        gbc.gridx = 1;
        gbc.gridwidth = 2;
        panel.add(field, gbc);
    }

    private boolean validateInput() {
        String name = nameField.getText().trim();
        String price = priceField.getText().trim();
        String stock = stockField.getText().trim();
        String imagePath = imagePathField.getText().trim();

        if (name.isEmpty()) {
            JOptionPane.showMessageDialog(this, "商品名称不能为空");
            return false;
        }

        try {
            Double.parseDouble(price);
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(this, "请输入有效的价格");
            return false;
        }

        try {
            Integer.parseInt(stock);
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(this, "请输入有效的库存数量");
            return false;
        }

        if (imagePath.isEmpty() || !new File(imagePath).exists()) {
            JOptionPane.showMessageDialog(this, "请选择有效的图片文件");
            return false;
        }

        return true;
    }

    private void updatePreview(String imagePath) {
        try {
            ImageIcon originalIcon = new ImageIcon(imagePath);
            Image image = originalIcon.getImage();
            Image scaledImage = image.getScaledInstance(100, 100, Image.SCALE_SMOOTH);
            previewLabel.setIcon(new ImageIcon(scaledImage));
        } catch (Exception e) {
            previewLabel.setIcon(null);
            previewLabel.setText("预览失败");
        }
    }

    public boolean showDialog() {
        setVisible(true);
        return confirmed;
    }

    public String getProductName() {
        return nameField.getText().trim();
    }

    public Double getPrice() {
        return Double.parseDouble(priceField.getText().trim());
    }

    public Integer getStock() {
        return Integer.parseInt(stockField.getText().trim());
    }

    public String getImagePath() {
        return imagePathField.getText().trim();
    }
} 